package com.mine.register;

import com.mine.common.URL;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author weixiao
 * @date 2025/3/31 14:48
 */
public class ServerRegister {

    private static final ConcurrentHashMap<String, List<URL>> MAP = new ConcurrentHashMap<>();

    public static void register(String interfaceName, URL url) {
        List<URL> urls = MAP.getOrDefault(interfaceName, new ArrayList<>());
        urls.add(url);
        MAP.put(interfaceName, urls);
        saveToFile();
    }

    private static void saveToFile() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\temp.txt"));
            oos.writeObject(MAP);
            oos.flush();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<URL> get(String interfaceName) {
        ConcurrentHashMap<String, List<URL>> map = getMap();
        return map.get(interfaceName);
    }

    private static ConcurrentHashMap<String, List<URL>> getMap() {
        ConcurrentHashMap<String, List<URL>> map = new ConcurrentHashMap<>();
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\temp.txt"));
            map = (ConcurrentHashMap<String, List<URL>>) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
